
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
        <div class="layui-card">
            <div class="layui-card-body">
            <div class="layui-btn-group" style="margin-bottom: 10px;width: 100%;">
                <button class="layui-btn layuiadmin-btn-tags" style="float: right;" data-type="add">添加书单</button> 	
            </div>
            
            <table class="layui-hide" id="test-table-operate" lay-filter="test-table-operate"></table>
            <script type="text/html" id="LAY-good-list-table-img">
	            <img src="{{d.list_image}}" alt="" style="width:126px; height: 87px;">
	        </script>
	        <script type="text/html" id="LAY-good-list-table-stock">
	            <p>{{d.book_num}}本</p>
	        </script>
	        <script type="text/html" id="LAY-good-list-table-stock1">
	            <p>{{parseInt(d.is_homepage) ==1?'是': '否'}}</p>
	        </script>
            <script type="text/html" id="test-table-operate-barDemo">
                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>
            </div>
        </div>
        </div>
    </div>
    </div>
<script>
layui.use(['admin', 'table', 'form', 'upload'], function(){
    var table = layui.table
    ,form = layui.form
    ,admin = layui.admin
    ,upload = layui.upload
    ,view = layui.view
    ,element = layui.element
    ,$ = layui.$
	,cols = [
		[
			{
				align: 'center',
				width: 130,
				templet: '#LAY-good-list-table-img',
				title: '列表封面图',
				field: 'list_image'
			}, {
				align: 'center',
				field: 'title',
				title: '书单标题'
			}, {
				align: 'center',
				field: 'book_num',
				title: '添加的书',
				templet: '#LAY-good-list-table-stock'
			}, {
				align: 'center',
				field: 'is_homepage',
				title: '是否推荐到首页',
				templet: '#LAY-good-list-table-stock1'
			}, {
				align: 'center',
				field: 'created_at',
				sort: true,
				title: '添加时间'
			}, {
				align: 'center',
				field: 'sort',
				title: '排序'
			}, {
				align: 'center',
				fixed: 'right',
				title: '操作',
				toolbar: '#test-table-operate-barDemo'
			}
		]
	];
	table.set({
		headers: { //通过 request 头传递
			'access-token': layui.data('layuiAdmin').access_token
		}
	});
	table.render({
		elem: '#test-table-operate',
		url: 'https://bookshop.dingdangtoy.com/api/admin/book_list/index',
		parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.message, //解析提示文本
				"data": res.data.items, //解析数据列表
				"count": res.data._meta.total_count //解析数据长度
				
			}
		},
		cols: cols,
		page: true
	});
    
    //监听工具条
    table.on('tool(test-table-operate)', function(obj){
      var data = obj.data;
      if(obj.event === 'edit'){
        admin.popup({
        title: '编辑书单'
        ,area: ['80%', '96%']
        ,id: 'LAY-popup-content-tags'
        ,success: function(layero, index){
          view(this.id).render('book-list/list/add', data).done(function(){
            form.render(null, 'layuiadmin-form-tags');    
                // 获取数据详情
            	$.ajax({
				    type: "GET",
				    dataType: "json",
				    url: "https://bookshop.dingdangtoy.com/api/admin/book_list/show?id="+ data.id,
				    data: {},
				    headers: { //通过 request 头传递
		              'access-token': layui.data('layuiAdmin').access_token
		            },
							success: function(data){
							    if (parseInt(data.code) == 0) {			
									var _html = '';
									for(var i = 0; i < data.data.items.length; i++) {
										_html += '<li data-id="'+data.data.items[i].book_id+'">'+
										  			'<div class="add-top">'+
										  				'<img src="'+data.data.items[i].image+'"/>'+
										  				'<div class="add-left">'+
										  					'<h3>'+data.data.items[i].title+'</h3>'+
										  					'<p>'+data.data.items[i].author+'</p>'+
										  				'</div>'+
										  				'<input type="button" value="移除这本书" class="layui-btn layui-btn1">'+
										  		    '</div>'+
										  		    '<textarea placeholder="在这里写下这本书的推荐语..." class="layui-textarea">'+data.data.items[i].message+'</textarea></li>';
								    }
									

								   $('#add-content').append(_html)
									form.render();
							    } else {
							    	layer.msg(data.message);
							    }
							},
							error: function(msg){
							  console.log(msg)
							}
					}); 
            // 搜索书籍 动态插入书籍
            $("#search_name").bind("input propertychange",function(event){
            	$('#book_list').show()
            	$('#book_list li').remove()
	   	        $.ajax({
				    type: "GET",
				    dataType: "json",
				    url: "https://bookshop.dingdangtoy.com/api/admin/book/search",
				    data: {
				    	'keyword':$('#search_name').val(),
				    },
				    headers: { //通过 request 头传递
		              'access-token': layui.data('layuiAdmin').access_token
		            },
							success: function(data){
							    if (parseInt(data.code) == 0) {
							    	console.log(data.data)
									var _html = '';
									for(var i = 0; i < data.data.items.length; i++) {
										_html  += '<li data-id="'+ data.data.items[i].id +'"><img src="' + data.data.items[i].image + '" alt="" /><div><h3>' + data.data.items[i].title + '</h3><p>' + data.data.items[i].author + '/' + data.data.items[i].publish_time + '</p></div></li>'
									}				
						            $("#book_list").append(_html);
									form.render();
							    } else {
							    	layer.msg(data.message);
							    }
							},
							error: function(msg){
							  console.log(msg)
							}
					}); 			    
			});
			// 点击插入书籍
			$('#book_list').delegate('li','click',function(){
			   var _html = '<li data-id="'+$(this).attr('data-id')+'">'+
					  			'<div class="add-top">'+
					  				'<img src="'+$(this).find('img').attr('src')+'"/>'+
					  				'<div class="add-left">'+
					  					'<h3>'+$(this).find('h3').text()+'</h3>'+
					  					'<p>'+$(this).find('p').text()+'</p>'+
					  				'</div>'+
					  				'<input type="button" value="移除这本书" class="layui-btn layui-btn1">'+
					  		    '</div>'+
					  		    '<textarea placeholder="在这里写下这本书的推荐语..." class="layui-textarea"></textarea></li>';
			   $('#add-content').append(_html)
			   $('#book_list').hide();
			    $("#search_name").val('')
			});
			// 移除书籍
			$('#add-content').delegate('.layui-btn1','click',function(){
			   $(this).get(0).parentNode.parentNode.remove()
			});
              //上传图片
			  upload.render({
				elem: '#add-goods-upload-btn',
				url: 'https://bookshop.dingdangtoy.com/api/admin/image/store',
				accept: 'images',
				method: 'get',
				acceptMime: 'image/*',
				done: function(res) {
					console.log(res.data.url)
					$('#add-goods-upload-img').attr('src', res.data.url);
					$('#add-goods-upload-image').val(res.data.url)
					//$(this.item).prev("div").children("input").val(res.data.url)
				}
			  }); 
			  upload.render({
				elem: '#add-goods-upload-btn1',
				url: 'https://bookshop.dingdangtoy.com/api/admin/image/store',
				accept: 'images',
				method: 'get',
				acceptMime: 'image/*',
				done: function(res) {
					console.log(res.data.url)
					$('#add-goods-upload-img1').attr('src', res.data.url);
					$('#add-goods-upload-image1').val(res.data.url)
					//$(this.item).prev("div").children("input").val(res.data.url)
				}
			  });
            //监听提交
            form.on('submit(layuiadmin-app-tags-submit)', function(data){	
              var arr1 = [];
               $('#add-content').find('li').each(function() {
                arr1.push({
                	'book_id': $(this).attr('data-id'),
                	'message': $(this).find('textarea').val()
                	
                })
               })
              arr1 = JSON.stringify(arr1)
              //提交 Ajax 成功后，关闭当前弹层并重载表格
			        layer.confirm('是否执行此操作', function(index){
			   	        $.ajax({
						    type: "PUT",
						    dataType: "json",
						    url: "https://bookshop.dingdangtoy.com/api/admin/book_list/update",
						    data: {
						    	'id':data.field.id,
						    	'title':data.field.title,
						    	'list_image':data.field.list_image,
						    	'detail_image':data.field.detail_image,
						    	'is_homepage':data.field.is_homepage,
						    	'sort':data.field.sort,
						    	'books': arr1
						    },
						    headers: { //通过 request 头传递
				              'access-token': layui.data('layuiAdmin').access_token
				            },
									success: function(data){
									    if (parseInt(data.code) == 0) {
									    	layer.msg('操作成功');
										    layui.table.reload('test-table-operate');
									    } else {
									    	layer.msg(data.message);
									    }
									},
									error: function(msg){
									  console.log(msg)
									}
							});
			        });			         
				layer.close(index); //执行关闭 
            });
          });
        }
      });
      } else if(obj.event === 'del'){
        layer.confirm('真的删除行么', function(index){
      		$.ajax({
				type: "DELETE",
				dataType: "json",
				url: "https://bookshop.dingdangtoy.com/api/admin/book_list/destroy",
				data: {
					id: data.id
				},
				headers: { //通过 request 头传递
					'access-token': layui.data('layuiAdmin').access_token
				},
				success: function(data) {
					layer.msg('操作成功');
					layui.table.reload('test-table-operate');
					layer.close(index); //执行关闭 
				},
				error: function(msg) {
					console.log(msg)
				}
			});
        });
      }
    });
  var active = {
    add: function(){
      admin.popup({
        title: '添加书单'
        ,area: ['80%', '100%']
        ,id: 'LAY-popup-content-tags'
        ,success: function(layero, index){
          view(this.id).render('book-list/list/add').done(function(){
            form.render(null, 'layuiadmin-form-tags');
            // 搜索书籍 动态插入书籍

            // 搜索书籍 动态插入书籍
            $("#search_name").bind("input propertychange",function(event){
            	$('#book_list').show()
            	$('#book_list li').remove()
	   	        $.ajax({
				    type: "GET",
				    dataType: "json",
				    url: "https://bookshop.dingdangtoy.com/api/admin/book/search",
				    data: {
				    	'keyword':$('#search_name').val(),
				    },
				    headers: { //通过 request 头传递
		              'access-token': layui.data('layuiAdmin').access_token
		            },
							success: function(data){
							    if (parseInt(data.code) == 0) {
							    	console.log(data.data)
									var _html = '';
									for(var i = 0; i < data.data.items.length; i++) {
										_html  += '<li data-id="'+ data.data.items[i].id +'"><img src="' + data.data.items[i].image + '" alt="" /><div><h3>' + data.data.items[i].title + '</h3><p>' + data.data.items[i].author + '/' + data.data.items[i].publish_time + '</p></div></li>'
									}				
						            $("#book_list").append(_html);
									form.render();
							    } else {
							    	layer.msg(data.message);
							    }
							},
							error: function(msg){
							  console.log(msg)
							}
					}); 			    
			});
			// 点击插入书籍
			$('#book_list').delegate('li','click',function(){
			   var _html = '<li data-id="'+$(this).attr('data-id')+'">'+
					  			'<div class="add-top">'+
					  				'<img src="'+$(this).find('img').attr('src')+'"/>'+
					  				'<div class="add-left">'+
					  					'<h3>'+$(this).find('h3').text()+'</h3>'+
					  					'<p>'+$(this).find('p').text()+'</p>'+
					  				'</div>'+
					  				'<input type="button" value="移除这本书" class="layui-btn layui-btn1">'+
					  		    '</div>'+
					  		    '<textarea placeholder="在这里写下这本书的推荐语..." class="layui-textarea"></textarea></li>';
			   $('#add-content').append(_html)
			   $('#book_list').hide();
			    $("#search_name").val('')
			});
			// 移除书籍
			$('#add-content').delegate('.layui-btn1','click',function(){
			   $(this).get(0).parentNode.parentNode.remove()
			});
              //上传图片
			  upload.render({
				elem: '#add-goods-upload-btn',
				url: 'https://bookshop.dingdangtoy.com/api/admin/image/store',
				accept: 'images',
				method: 'get',
				acceptMime: 'image/*',
				done: function(res) {
					console.log(res.data.url)
					$('#add-goods-upload-img').attr('src', res.data.url);
					$('#add-goods-upload-image').val(res.data.url)
					//$(this.item).prev("div").children("input").val(res.data.url)
				}
			  }); 
			  upload.render({
				elem: '#add-goods-upload-btn1',
				url: 'https://bookshop.dingdangtoy.com/api/admin/image/store',
				accept: 'images',
				method: 'get',
				acceptMime: 'image/*',
				done: function(res) {
					console.log(res.data.url)
					$('#add-goods-upload-img1').attr('src', res.data.url);
					$('#add-goods-upload-image1').val(res.data.url)
					//$(this.item).prev("div").children("input").val(res.data.url)
				}
			  });
            //监听提交
            form.on('submit(layuiadmin-app-tags-submit)', function(data){	
              var arr1 = [];
               $('#add-content').find('li').each(function() {
                arr1.push({
                	'book_id': $(this).attr('data-id'),
                	'message': $(this).find('textarea').val()
                	
                })
               })
              arr1 = JSON.stringify(arr1)
              //提交 Ajax 成功后，关闭当前弹层并重载表格
			        layer.confirm('是否执行此操作', function(index){
			   	        $.ajax({
						    type: "POST",
						    dataType: "json",
						    url: "https://bookshop.dingdangtoy.com/api/admin/book_list/store",
						    data: {
						    	'title':data.field.title,
						    	'list_image':data.field.list_image,
						    	'detail_image':data.field.detail_image,
						    	'is_homepage':data.field.is_homepage,
						    	'sort':data.field.sort,
						    	'books': arr1
						    },
						    headers: { //通过 request 头传递
				              'access-token': layui.data('layuiAdmin').access_token
				            },
									success: function(data){
									    if (parseInt(data.code) == 0) {
									    	layer.msg('操作成功');
										    layui.table.reload('test-table-operate');
									    } else {
									    	layer.msg(data.message);
									    }
									},
									error: function(msg){
									  console.log(msg)
									}
							});
			        });			         
				layer.close(index); //执行关闭 
            });
          });
        }
      });
    }
    }
    
  $('.layui-btn.layuiadmin-btn-tags').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  }); 
  
  });
</script>
<style type="text/css">
	.layui-table-cell, .layui-table-tool-panel li{white-space: inherit !important;}
</style>